package com.xhh.greynewsapp.fragment.news;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.xhh.greynewsapp.R;
import com.xhh.greynewsapp.adapter.NewsRecyclerViewAdapter;
import com.xhh.greynewsapp.model.topnews.NewsData;
import com.xhh.greynewsapp.model.topnews.NewsTop;
import com.xhh.greynewsapp.utils.HttpUtils;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @description
 * @author: weiXhh
 * @create: 2020-05-27 11:11
 **/
public class NewsTopFragment extends Fragment {

    @BindView(R.id.news_recommend_recycler_view)
    RecyclerView recyclerView;

    @BindView(R.id.swipe_fresh_news_recommend)
    SwipeRefreshLayout swipeRefreshLayout;

    private static final String TAG = "NewsTopFragment";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_top, container, false);
        ButterKnife.bind(this, view);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        initRefresh();

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // TODO 从接口获取数据保存到数据库，停止刷新,接口限制,没有做
                        initRefresh();
                    }
                }, 2000);
            }
        });


        return view;
    }

    private void initRefresh() {

        // 从数据库查询数据, TODO 头条可使用接口,这里不使用了,限制10条
        List<NewsData> all = LitePal
                .limit(10)
                .order("create_date desc")
                .find(NewsData.class);

        if (all != null || all.size() > 0) {
            // 数据库中表中有数据
            Log.e(TAG, all.toString());

            swipeRefreshLayout.setRefreshing(false);
            recyclerView.setAdapter(new NewsRecyclerViewAdapter(all));

        } else {
            // 从接口中获取
            getDataByApi();
            initRefresh();
        }


    }

    private void getDataByApi() {
        String url = "http://v.juhe.cn/toutiao/index?type=top&key=5dabcae83cf9a18e43c3f841f89ee435";
        HttpUtils.get(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG, e.getMessage().toString());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                NewsTop newsTop = gson.fromJson(string, NewsTop.class);
                List<NewsData> data = newsTop.getResult().getData();
                for (NewsData datum : data) {
                    NewsData newsData = new NewsData();
                    newsData.setUniquekey(datum.getUniquekey());
                    newsData.setAuthor_name(datum.getAuthor_name());
                    newsData.setTitle(datum.getTitle());
                    newsData.setDate(datum.getDate());
                    newsData.setCategory(datum.getCategory());
                    newsData.setUrl(datum.getUrl());
                    newsData.setThumbnail_pic_s(datum.getThumbnail_pic_s());
                    newsData.setThumbnail_pic_s02(datum.getThumbnail_pic_s02());
                    newsData.setThumbnail_pic_s03(datum.getThumbnail_pic_s03());
                    // 保存数据的时间，根据这个排序
                    newsData.setCreate_date(new Date());
                    newsData.save();
                }
            }
        });
    }
}
